import { app } from "../../scripts/app.js";
import { logger } from "./logger.js";

// 自定义 Widget 类 - 用于测试 addCustomWidget
class CustomProgressWidget {
    constructor() {
        this.value = null;
        this.element = null;
        this.node = null;
        this.name = null;
        this.type = "custom_progress";
        console.log("[CustomWidget] 创建自定义进度 Widget");
    }

    init(node, name, inputData) {
        console.log("[CustomWidget] 初始化:", { 
            node: node?.type, 
            name, 
            inputData 
        });
        
        this.node = node;
        this.name = name;
        this.value = inputData?.default || 0;
        this.element = this.createElement();
        
        return this;
    }

    createElement() {
        console.log("[CustomWidget] 创建元素");
        
        const container = document.createElement("div");
        container.style.width = "100%";
        container.style.padding = "8px";
        container.style.backgroundColor = "var(--comfy-input-bg)";
        container.style.border = "2px solid var(--border-color)";
        container.style.borderRadius = "8px";
        container.style.margin = "4px 0";
        
        // 创建标题
        const title = document.createElement("div");
        title.style.fontSize = "12px";
        title.style.color = "var(--input-text)";
        title.style.marginBottom = "4px";
        title.textContent = "自定义进度条";
        
        // 创建进度条
        const progressBar = document.createElement("div");
        progressBar.style.width = "100%";
        progressBar.style.height = "16px";
        progressBar.style.backgroundColor = "var(--border-color)";
        progressBar.style.borderRadius = "8px";
        progressBar.style.overflow = "hidden";
        progressBar.style.position = "relative";
        
        // 创建进度填充
        const progressFill = document.createElement("div");
        progressFill.style.width = "0%";
        progressFill.style.height = "100%";
        progressFill.style.backgroundColor = "#00ff00";
        progressFill.style.transition = "width 0.3s ease";
        progressFill.style.position = "absolute";
        progressFill.style.top = "0";
        progressFill.style.left = "0";
        
        // 创建文本覆盖
        const textOverlay = document.createElement("div");
        textOverlay.style.position = "absolute";
        textOverlay.style.top = "0";
        textOverlay.style.left = "0";
        textOverlay.style.width = "100%";
        textOverlay.style.height = "100%";
        textOverlay.style.display = "flex";
        textOverlay.style.alignItems = "center";
        textOverlay.style.justifyContent = "center";
        textOverlay.style.fontSize = "10px";
        textOverlay.style.color = "#000";
        textOverlay.style.fontWeight = "bold";
        textOverlay.textContent = "0%";
        
        progressBar.appendChild(progressFill);
        progressBar.appendChild(textOverlay);
        container.appendChild(title);
        container.appendChild(progressBar);
        
        // 保存引用
        this.progressFill = progressFill;
        this.textOverlay = textOverlay;
        
        return container;
    }

    getValue() {
        return this.value;
    }

    setValue(value, triggerChange = true) {
        if (this.value !== value) {
            this.value = value;
            
            // 更新UI
            if (this.progressFill && this.textOverlay) {
                const percentage = Math.min(100, Math.max(0, value));
                this.progressFill.style.width = `${percentage}%`;
                this.textOverlay.textContent = `${Math.round(percentage)}%`;
            }
            
            if (triggerChange && this.node) {
                this.node.onWidgetChanged?.(this.name, this.value);
            }
        }
    }

    serialize() {
        return this.value;
    }
}

// 自定义 DOM Widget 类 - 用于测试 addDOMWidget
class CustomDOMWidget {
    constructor() {
        this.value = null;
        this.element = null;
        this.node = null;
        this.name = null;
        this.type = "custom_dom";
        console.log("[CustomDOMWidget] 创建自定义 DOM Widget");
    }

    init(node, name, inputData) {
        console.log("[CustomDOMWidget] 初始化:", { 
            node: node?.type, 
            name, 
            inputData 
        });
        
        this.node = node;
        this.name = name;
        this.value = inputData?.default || "默认值";
        this.element = this.createElement();
        
        return this;
    }

    createElement() {
        console.log("[CustomDOMWidget] 创建 DOM 元素");
        
        const container = document.createElement("div");
        container.style.width = "100%";
        container.style.padding = "8px";
        container.style.backgroundColor = "var(--comfy-input-bg)";
        container.style.border = "2px solid var(--border-color)";
        container.style.borderRadius = "8px";
        container.style.margin = "4px 0";
        
        // 创建标题
        const title = document.createElement("div");
        title.style.fontSize = "12px";
        title.style.color = "var(--input-text)";
        title.style.marginBottom = "4px";
        title.textContent = "自定义 DOM 控件";
        
        // 创建输入框
        const input = document.createElement("input");
        input.type = "text";
        input.value = this.value;
        input.placeholder = "输入文本...";
        input.style.width = "100%";
        input.style.padding = "4px";
        input.style.border = "1px solid var(--border-color)";
        input.style.borderRadius = "2px";
        input.style.backgroundColor = "var(--comfy-input-bg)";
        input.style.color = "var(--input-text)";
        input.style.marginBottom = "4px";
        
        // 创建按钮
        const button = document.createElement("button");
        button.textContent = "更新";
        button.style.width = "100%";
        button.style.padding = "4px";
        button.style.backgroundColor = "var(--comfy-input-bg)";
        button.style.color = "var(--input-text)";
        button.style.border = "1px solid var(--border-color)";
        button.style.borderRadius = "2px";
        button.style.cursor = "pointer";
        
        // 创建状态显示
        const status = document.createElement("div");
        status.style.fontSize = "10px";
        status.style.color = "var(--input-text)";
        status.style.marginTop = "4px";
        status.textContent = `当前值: ${this.value}`;
        
        // 事件处理
        input.addEventListener("input", (e) => {
            this.value = e.target.value;
            status.textContent = `当前值: ${this.value}`;
        });
        
        button.addEventListener("click", () => {
            console.log("[CustomDOMWidget] 按钮点击，当前值:", this.value);
            status.textContent = `已更新: ${this.value}`;
        });
        
        container.appendChild(title);
        container.appendChild(input);
        container.appendChild(button);
        container.appendChild(status);
        
        this.input = input;
        this.status = status;
        
        return container;
    }

    getValue() {
        return this.value;
    }

    setValue(value, triggerChange = true) {
        this.value = value;
        if (this.input) {
            this.input.value = value;
        }
        if (this.status) {
            this.status.textContent = `当前值: ${value}`;
        }
        
        if (triggerChange && this.node) {
            this.node.onWidgetChanged?.(this.name, this.value);
        }
    }

    serialize() {
        return this.value;
    }
}

class Custom {
    hello() { console.log("hello"); }
}
app.registerExtension({
    name: "custom.progressbar",
    async nodeCreated(node) {
        // 只处理 ComplexUITestNode 节点
        if (node.constructor.comfyClass !== "ComplexUITestNode") return;
        logger.analyzeObject(node,"progress_bar");
        

        console.log(typeof Custom); // function
        console.log(Custom.prototype); // { constructor: ..., hello: ... }
        const a = new Custom();
        console.log(a.__proto__ === Custom.prototype); // true
        a.hello(); // 输出 hello

       
        

        // 添加状态文本
        const statusWidget = node.addWidget("text", "训练状态", "", (value) => {
            console.log("[LoRA调试] 状态更新:", value);
        }, {
            multiline: false,
            readonly: true
        });
        console.log("[LoRA调试] 状态文本小部件已添加:", statusWidget);
        
        // 添加按钮
        const buttonWidget = node.addWidget("button", "upload 3d model", "upload3dmodel", () => {
            console.log("[ProgressBar] 按钮被点击");
        });
        console.log("[ProgressBar] 按钮小部件已添加:", buttonWidget);
        
        // 添加滑块
        const slider = node.addWidget("slider", "训练进度", 50, (value) => {
            console.log("[ProgressBar] 进度变化:", value);
        }, {
            min: 0,
            max: 100,
            step: 1,
            readonly: true
        });
        slider.options = { min: 0, max: 100 };
        console.log("[ProgressBar] 滑块小部件已添加:", slider);
        
        // ===== 测试 2: addCustomWidget =====
        console.log("[ProgressBar] 测试 2: addCustomWidget");
        
        try {
            // 检查是否有 addCustomWidget 方法
            if (typeof node.addCustomWidget === 'function') {
                console.log("[ProgressBar] 节点支持 addCustomWidget 方法");
                
                // 创建自定义 Widget 实例
                const customWidget = new CustomProgressWidget();
                customWidget.init(node, "custom_progress", {
                    default: 25,
                    description: "自定义进度条测试"
                });
                
                // 使用 addCustomWidget 方法
                const customResult = node.addCustomWidget(customWidget);
                console.log("[ProgressBar] addCustomWidget 调用结果:", customResult);
                
                // 测试更新自定义 Widget
                setTimeout(() => {
                    customWidget.setValue(75);
                    console.log("[ProgressBar] 自定义 Widget 值已更新为 75");
                }, 2000);
                
            } else {
                console.log("[ProgressBar] 节点不支持 addCustomWidget 方法");
                
                // 手动添加到 widgets 数组
                const customWidget = new CustomProgressWidget();
                customWidget.init(node, "manual_custom_progress", {
                    default: 30,
                    description: "手动添加的自定义进度条"
                });
                
                if (!node.widgets) {
                    node.widgets = [];
                }
                node.widgets.push(customWidget);
                console.log("[ProgressBar] 手动添加自定义 Widget 成功");
            }
        } catch (error) {
            console.error("[ProgressBar] addCustomWidget 测试失败:", error);
        }
        
        // ===== 测试 3: addDOMWidget =====
        console.log("[ProgressBar] 测试 3: addDOMWidget");
        
        try {
            // 检查是否有 addDOMWidget 方法
            if (typeof node.addDOMWidget === 'function') {
                console.log("[ProgressBar] 节点支持 addDOMWidget 方法");
                
                // 创建自定义 DOM 元素
                const domElement = document.createElement("div");
                domElement.style.padding = "8px";
                domElement.style.backgroundColor = "var(--comfy-input-bg)";
                domElement.style.border = "2px solid var(--border-color)";
                domElement.style.borderRadius = "4px";
                domElement.style.margin = "4px 0";
                
                // 添加内容
                const title = document.createElement("div");
                title.textContent = "DOM Widget 测试";
                title.style.fontSize = "12px";
                title.style.color = "var(--input-text)";
                title.style.marginBottom = "4px";
                
                const content = document.createElement("div");
                content.textContent = "这是一个通过 addDOMWidget 添加的自定义 DOM 元素";
                content.style.fontSize = "10px";
                content.style.color = "var(--input-text)";
                
                const testButton = document.createElement("button");
                testButton.textContent = "DOM 测试按钮";
                testButton.style.width = "100%";
                testButton.style.padding = "4px";
                testButton.style.marginTop = "4px";
                testButton.style.backgroundColor = "var(--comfy-input-bg)";
                testButton.style.color = "var(--input-text)";
                testButton.style.border = "1px solid var(--border-color)";
                testButton.style.borderRadius = "2px";
                testButton.style.cursor = "pointer";
                
                testButton.addEventListener("click", () => {
                    console.log("[ProgressBar] DOM Widget 按钮被点击");
                    content.textContent = "DOM Widget 按钮被点击了！";
                });
                
                domElement.appendChild(title);
                domElement.appendChild(content);
                domElement.appendChild(testButton);
                
                // 使用 addDOMWidget 方法
                const domResult = node.addDOMWidget("dom_test", "div", domElement, {
                    serialize: false,
                    hideOnZoom: false
                });
                console.log("[ProgressBar] addDOMWidget 调用结果:", domResult);
                
            } else {
                console.log("[ProgressBar] 节点不支持 addDOMWidget 方法");
                
                // 创建自定义 DOM Widget 实例
                const domWidget = new CustomDOMWidget();
                domWidget.init(node, "manual_dom_widget", {
                    default: "手动 DOM Widget",
                    description: "手动添加的 DOM Widget"
                });
                
                if (!node.widgets) {
                    node.widgets = [];
                }
                node.widgets.push(domWidget);
                console.log("[ProgressBar] 手动添加 DOM Widget 成功");
            }
        } catch (error) {
            console.error("[ProgressBar] addDOMWidget 测试失败:", error);
        }
        
        // ===== 测试 4: 混合使用 =====
        console.log("[ProgressBar] 测试 4: 混合使用");
        
        // 添加一个组合控件
        const comboWidget = node.addWidget("combo", "测试选项", "选项1", (value) => {
            console.log("[ProgressBar] 选项变化:", value);
        }, {
            options: ["选项1", "选项2", "选项3"]
        });
        console.log("[ProgressBar] 组合小部件已添加:", comboWidget);
        
        // 添加布尔控件
        const booleanWidget = node.addWidget("boolean", "启用测试", false, (value) => {
            console.log("[ProgressBar] 布尔值变化:", value);
        });
        console.log("[ProgressBar] 布尔小部件已添加:", booleanWidget);
        
        // 显示所有 widgets
        console.log("[ProgressBar] 所有 widgets:", node.widgets);
        console.log("[ProgressBar] widgets 数量:", node.widgets ? node.widgets.length : 0);
        
        // 更新画布
        node.setDirtyCanvas(true);
        console.log("[ProgressBar] 画布已标记为需要重绘");
        
        node._customProgressBar = true;
        console.log("[ProgressBar] 进度条测试完成");
    }
});

app.registerExtension({
    name: "custom.progressbar.drawbg",
    async beforeRegisterNodeDef(nodeType, nodeData, app) {
        if (nodeType.prototype.constructor.comfyClass !== "ComplexUITestNode") return;
        // 或者 nodeType.comfyClass
        // 绘制背景红色边框
        nodeType.prototype.onDrawBackground = function(ctx) {
            ctx.save();
            ctx.strokeStyle = "#ff0000";
            ctx.lineWidth = 4;
            ctx.strokeRect(2, 2, this.size[0] - 4, this.size[1] - 4);
            ctx.restore();
        };
        // 可选：绘制前景绿色边框
        nodeType.prototype.onDrawForeground = function(ctx) {
            ctx.save();
            ctx.strokeStyle = "#00ff00";
            ctx.lineWidth = 2;
            ctx.strokeRect(6, 6, this.size[0] - 12, this.size[1] - 12);
            ctx.restore();
        };
    }
});